package advalidator

import (
	"fmt"
	"time"
	"yunj/app/enum/adenum"
	"yunj/app/model"
	"yunj/pkg/yunj/app/enum/stateenum"
	"yunj/pkg/yunj/util"

	"github.com/worklz/go-validate"
)

type Ad struct {
	validate.Validator
}

func (v *Ad) HandleDatas(datas map[string]interface{}, scene string) (err error) {
	if scene == "FormSubmit" {
		err = v.HandleDatasByFormSubmit(datas)
		if err != nil {
			return
		}
	}
	return
}

func (v *Ad) HandleDatasByFormSubmit(datas map[string]interface{}) (err error) {
	currTime := time.Now().In(time.Local)
	dbAd := &model.Ad{
		Cover: util.MapKeyValue(datas, "cover", ""),
		Link:  util.MapKeyValue(datas, "link", ""),
		Desc:  util.MapKeyValue(datas, "desc", ""),
	}
	// valid_time
	validTimeStr := util.MapKeyValue(datas, "valid_time", "")
	if validTimeStr != "" {
		var validTime time.Time
		validTime, err = time.Parse("2006-01-02 15:04:05", validTimeStr)
		if err != nil {
			err = fmt.Errorf("有效期%s解析出错:%v", validTimeStr, err)
			return
		}
		dbAd.ValidTime = validTime.Unix()
	}
	// last_update_time
	dbAd.LastUpdateTime = currTime.Unix()
	// status
	if statusRaw, exists := datas["status"]; exists {
		if statusValue, ok := adenum.StatusEnum.IsValue(statusRaw); ok {
			dbAd.Status = statusValue
		}
	}
	// location
	if locationRaw, exists := datas["location"]; exists {
		if locationValue, ok := adenum.LocationEnum.IsValue(locationRaw); ok {
			dbAd.Location = locationValue
		}
	}
	// id
	var id uint64
	if idRaw, exists := datas["id"]; exists {
		var idVal uint64
		if idVal, err = util.ToUint64(idRaw); err == nil && idVal > 0 {
			id = idVal
		}
	}
	if id > 0 {
		// 编辑
		dbAd.Id = id
	} else {
		// 新增
		dbAd.CreateTime = currTime.Unix()
		dbAd.State = stateenum.NORMAL
	}
	datas["dbAd"] = dbAd
	return
}
